<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="lib/index.js"></script>
    <script src="./jquery.min.js"></script>
    <script src="./axios.min.js"></script>
    <style>
        .main {
            width: 800px;
            min-height: 200px;
            padding-bottom: 20px;
            margin: 100px;
            background-color: #f5f5f5;
            display: flex;
            flex-direction: column;
            position: relative;
        }

        .percentage {
            width: 200px;
            height: 20px;
            background-color: #FFB6C1;
            display: flex;
            margin: 0 20px;
        }

        .percentage>span {
            width: 40%;
            height: 100%;
            background-color: #FFD700;
        }

        .file-name {
            width: 200px;
            color: #333;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;

        }

        .file-wrap {
            width: 100%;
            height: 40px;
            display: flex;
            align-items: center;
            margin-top: 20px;
            padding: 0 20px;
            box-sizing: border-box;
        }

        .size {
            width: 240px;
        }

        .switch {
            width: 60px;
            height: 26px;
        }

        .status {
            width: 100px;
            margin-right: 10px;
            color: #888;
        }

        #import {
            width: 100px;
            height: 26px;
            position: absolute;
            left: 50%;
            bottom: -50px;
            transform: translateX(-50%);
        }
    </style>
</head>

<body>
    <div class="main">
        <button id="import">选择文件</button>
    </div>
    <script>
        const host = ''
        $('#import').click(async () => {
            /* 文件选择框 */
            const files = await FileChunk.FilelShow()
            /* 遍历文件列表 */
            files.map((file) => Filelist(file))

            function Filelist(file) {

                /* 创建FileChunk实例（每个文件一个实例） */
                const chunk = new FileChunk({
                    url: `${host}/transmission/chunk-upload`,
                    file,
                    chunkSize: 0.1 * 1024 * 1024
                });

                const div = document.createElement('div')
                div.className = 'file-wrap'
                div.id = chunk.chunkId
                div.innerHTML = ` <div class="file-name">${file.name}</div>
                 <div class="percentage">
                <span></span>
                 </div>
                 <span class="status">读取中</span>
                <span class="size">0B/${FileChunk.formatSize(chunk.file.size)}</span>`
                /* 页面渲染 */
                const button = document.createElement('button')

                button.id = "btn_" + chunk.chunkId

                button.style.width = '50px'

                button.innerText = '暂停'

                button.disabled = true

                button.onclick = function () {
                    console.log(chunk.readFileStatus);
                    chunk.chunkSwitch()
                    if (chunk.status) {
                        button.innerText = '暂停'
                    } else {
                        button.innerText = '续传'
                    }
                }

                div.appendChild(button)

                $('.main').append(div)


                /* 返回一个FormData实例对象，注入chunk作为单次切片的上传数据 */
                chunk.formdata = (fileId, file, index) => {
                    // 创建数据容器
                    const formdata = new FormData();
                    // 文件ID（随内存清空）
                    formdata.append("fileId", fileId);
                    // 文件切片下标
                    formdata.append("index", index.toString());
                    // 文件切片
                    formdata.append("file", file);
                    /* 将数据注入FileChunk实例对象 */
                    return formdata;
                }



                /* 文件读取中 */
                chunk.onReadFile = (num) => {
                    $(`#${chunk.chunkId} .percentage span`).css('width', num + '%')
                    $(`#${chunk.chunkId} .percentage span`).css('backgroundColor', '#C71585')
                    if (num >= 100) {
                        $("#btn_" + chunk.chunkId).attr('disabled', false)
                    }
                }

                /* 文件读取失败 */
                chunk.onReadFileErr = (err) => {
                    console.log('文件读取失败');
                }

                /* 文件读取完毕 */
                chunk.onReadFileEnd = async (fileId, send) => {
                    const { data } = await axios.post(
                        `${host}/transmission/chunk-read`,
                        { fileId }
                    );
                    if (data.sliceChunks.length > 0) {
                        send(data.sliceChunks)
                    } else {
                        send()
                    }

                }


                /* 切片上传中 */
                chunk.onSingleChange = (progress, data) => {
                    /* 切换状态 */
                    $(`#${chunk.chunkId} .status`).text('上传中')
                    /* 更新文件大小 */
                    $(`#${chunk.chunkId} .size`).text(`${FileChunk.formatSize(progress.current)}/${FileChunk.formatSize(chunk.file.size)}`)
                    /* 更新进度条 */
                    $(`#${chunk.chunkId} .percentage span`).css('width', FileChunk.formatPercentage(progress.current, chunk.file.size) + '%')
                    /* 根据状态改变进度条颜色 */
                    $(`#${chunk.chunkId} .percentage span`).css('backgroundColor', '#EE82EE')
                    /*  */
                }

                /* 上传失败 */
                chunk.onFailureChange = () => {
                    console.log('上传失败');
                }

                /* 文件上传完毕 */
                chunk.onAllChange = async () => {
                    /* 切换状态 */
                    $(`#${chunk.chunkId} .status`).text('写入中')
                    /* 禁用续传/暂停按钮 */
                    $("#btn_" + chunk.chunkId).attr('disabled', true)
                    /* 根据状态改变进度条颜色 */
                    $(`#${chunk.chunkId} .percentage span`).css('backgroundColor', '#FF00FF')
                    /* 创建数据容器，文件id，写入路径，文件名称（如果有其他的可以自己添加） */
                    const formdata = new FormData();
                    // 文件ID（随内存清空）
                    formdata.append("fileId", chunk.fileId);
                    formdata.append("fileName", chunk.file.name);
                    const { data } = await axios.post(
                        `${host}/transmission/chunk-all`,
                        formdata
                    );
                    /* 切换状态 */
                    $(`#${chunk.chunkId} .status`).text('上传完毕')
                    /* 根据状态改变进度条颜色 */
                    $(`#${chunk.chunkId} .percentage span`).css('backgroundColor', '#32CD32')
                }

                /* 数据停止传输（暂停了） */
                chunk.onStop = () => {
                    console.log("数据停止传输（暂停了）");
                }

                /* 开始读取文件 */
                chunk.readFileSync()

            }





        })

    </script>
</body>

</html>